package com.smartsofa.main;

import java.io.File;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.smartsofa.R;
import com.smartsofa.fragment.AssessFragment;
import com.smartsofa.fragment.CircleFragment;
import com.smartsofa.fragment.FamilyFragment;
import com.smartsofa.fragment.KnowledgeFragment;
import com.smartsofa.fragment.MenuListFragment;
import com.smartsofa.util.AsyncImageLoader;
import com.smartsofa.util.CircleImageView;
import com.smartsofa.util.MyUtils;
import com.smartsofa.util.SlidingFragmentActivity;
import com.smartsofa.util.SlidingMenu;

public class MainActivity extends SlidingFragmentActivity implements OnClickListener {
/** 
 * ���������֡���ͥȦ��֪ʶ��������fragment
 * */
	private AssessFragment assessFrag;
	private FamilyFragment familyFrag;
	private KnowledgeFragment knowledgeFrag;
	private CircleFragment circleFrag;
/**
 * ��fragment�Ĳ���
 */
	private View assessLayout;

	private View knowledgeLayout;
	private View circleLayout;
	
	//定义用户头像按钮
	private CircleImageView img_button;
	private Boolean flag = false;
	//定义用户头像地址
	private String user_img_url="";
/**
 * ��Tab��������ʾ��ͼ��ͱ���Ŀؼ�
 */	
	private ImageView assessImage;
	
	private ImageView knowledgeImage;
	private ImageView circleImage;
	private ImageView reddot;
	boolean netstate;
	
	private View assessLine;
	
	private View knowledgeLine;
	private View circleLine;
	
	private Button bt_firstpage;
	private Button bt_family;
	private Button bt_message;
	private TextView tx_circle;
	private TextView tx_knowledge;
	private TextView icon1_text;
	private TextView icon2_text;
	private TextView icon3_text;
	private ImageView user_image;
	
	private JSONObject msg_json;
	private JSONObject msg_reply_json;
	
	public static JSONArray message = null;
	public static JSONArray replyMessageArray = null;
/**
 * ���ڶ�Fragment���й���
 */	
	private FragmentManager fragmentManager;
	
/**
 * ����ѡ��fragment
 */
    int selectionState=0;
    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;
    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		fragmentManager=getSupportFragmentManager();
		selectionState=getSelectionState();		
		setTabSelection(selectionState);
		initSlidingMenu(savedInstanceState);
		netstate=MyUtils.isNetworkConnected(getApplicationContext());		
		if(!netstate){
			Toast.makeText(MainActivity.this,"世界上最遥远的距离就是没有网络！",Toast.LENGTH_SHORT).show();
		}else{
		
			Thread thread = new Thread(new getMessageFromServer1());
			thread.start();
			Thread thread2 = new Thread(new getMessageFromServer2());
			thread2.start();}
		
	}
	
	
	/**
	 * 初始化视图
	 */
	private void initView() {
		img_button=(CircleImageView) findViewById(R.id.main_user_img);
		
		assessLayout = findViewById(R.id.icon1_lay);
		circleLayout = findViewById(R.id.icon2_lay);
		knowledgeLayout = findViewById(R.id.icon3_lay);
		assessLine=findViewById(R.id.icon1_line);
		circleLine=findViewById(R.id.icon2_line);
		knowledgeLine=findViewById(R.id.icon3_line);
		assessImage = (ImageView) findViewById(R.id.icon1);
		circleImage = (ImageView) findViewById(R.id.icon2);
		knowledgeImage = (ImageView) findViewById(R.id.icon3);
		reddot = (ImageView) findViewById(R.id.reddot);
		bt_firstpage=(Button) findViewById(R.id.bt_firstpage);
		bt_family=(Button) findViewById(R.id.bt_family);
		tx_circle=(TextView) findViewById(R.id.tx_circle);
		tx_knowledge=(TextView)findViewById(R.id.tx_knowledge);
		assessLayout.setOnClickListener(this);
		circleLayout.setOnClickListener(this);
		knowledgeLayout.setOnClickListener(this);
		bt_message = (Button) findViewById(R.id.bt_msg);
		/**
		 * 用户头像下载
		 */
		user_image = (ImageView) findViewById(R.id.main_user_img);
		SharedPreferences userinfo = getSharedPreferences("userInformation", 0);
		user_img_url= userinfo.getString("imageurl", "");
		/**
		 * 判断本地是否有缓存的图片,如果没有才去下载
		 */
		String imagefileString  = Environment.getExternalStorageDirectory() +"/user_img_"+MyUtils.getUSERID()+".png";
	    File file = new File(imagefileString);
	    if(!file.exists()&&!user_img_url.equals("")){
			AsyncImageLoader imageLoader=new AsyncImageLoader(getApplicationContext());
			Bitmap bitmap = imageLoader.loadImage(user_image, user_img_url);
			if (bitmap != null) {
				user_image.setImageBitmap(bitmap);
				MyUtils.setPicToStore(MyUtils.getUSERID(),bitmap);
			}
		}
		
		String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
		String fileName = "/user_img_"+MyUtils.getUSERID()+".png";
		Bitmap bitmap = BitmapFactory.decodeFile(baseDir+fileName);
		if(bitmap != null){
			user_image.setImageBitmap(bitmap);
		}
		else{
			
		}
		
		icon1_text=(TextView)findViewById(R.id.icon1_text);
		icon2_text=(TextView)findViewById(R.id.icon2_text);
		icon3_text=(TextView)findViewById(R.id.icon3_text);

		bt_family.setOnClickListener(this);
		bt_firstpage.setOnClickListener(this);
		
		bt_message.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, UserMessage.class);
				startActivity(intent);
				reddot.setVisibility(View.INVISIBLE);
			}
		});
		
	}
	
	private void initSlidingMenu(Bundle savedInstanceState) {
		//初始化slidingMenu 
		setBehindContentView(R.layout.fragment_bacmenu);
		getSupportFragmentManager().beginTransaction().replace(R.id.fragment_bacmenu, new MenuListFragment()).commit();		

		//获得slidingMenu对象 
		final SlidingMenu sm = getSlidingMenu();
		// 设置slidingMenu宽度 
		//sm.setBehindWidth(R.dimen.slidingmenu_offset);//设置菜单的宽
		sm.setBehindWidth(getApplicationContext().getResources().getDisplayMetrics().widthPixels/2);//设置菜单的宽
//		sm.setBehindOffsetRes(getApplicationContext().getResources().getDisplayMetrics().widthPixels/8);
		// 设置渐入渐出效果的值 
		sm.setFadeDegree(0.35f);
		// 设置滑动触摸模式 
//		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);		
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);//边缘滑动侧滑出菜单
		img_button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				sm.toggle();
			}
		});
	}
	
	private void setTabSelection(int index) {
			FragmentTransaction transaction = fragmentManager.beginTransaction();
			hideFragments(transaction);
			int lightgreen= getResources().getColor(R.color.lightgreen);
			int white=getResources().getColor(R.color.white);
			int gray=getResources().getColor(R.color.darkgray);
			switch (index) {
			case 0:
				// 健康信息——个人
				assessImage.setImageResource(R.drawable.frag_assess_on);
				circleImage.setImageResource(R.drawable.frag_circle);
				knowledgeImage.setImageResource(R.drawable.frag_knowledge);
				bt_firstpage.setBackgroundResource(R.drawable.bt_top_left_on);
				bt_family.setVisibility(View.VISIBLE);
				bt_firstpage.setVisibility(View.VISIBLE);
				tx_circle.setVisibility(View.INVISIBLE);
				tx_knowledge.setVisibility(View.INVISIBLE);
				bt_family.setBackgroundResource(R.drawable.bt_top_rshift);
				bt_firstpage.setTextColor(lightgreen);
				bt_family.setTextColor(white);
				assessLine.setVisibility(View.VISIBLE);
				circleLine.setVisibility(View.INVISIBLE);
				knowledgeLine.setVisibility(View.INVISIBLE);
				icon1_text.setTextColor(lightgreen);
				icon2_text.setTextColor(gray);
				icon3_text.setTextColor(gray);
				
				
				if (assessFrag == null) {
					assessFrag = new AssessFragment();
					transaction.add(R.id.body_frame, assessFrag);
				} else {
					transaction.show(assessFrag);
				}
				break;
			
			case 1:
				// 健康社区
				assessImage.setImageResource(R.drawable.frag_assess);
				circleImage.setImageResource(R.drawable.frag_circle_on);
				knowledgeImage.setImageResource(R.drawable.frag_knowledge);
				bt_family.setVisibility(View.INVISIBLE);
				bt_firstpage.setVisibility(View.INVISIBLE);
				tx_circle.setVisibility(View.VISIBLE);
				tx_knowledge.setVisibility(View.INVISIBLE);
				assessLine.setVisibility(View.INVISIBLE);
				circleLine.setVisibility(View.VISIBLE);
				knowledgeLine.setVisibility(View.INVISIBLE);
				icon2_text.setTextColor(lightgreen);
				icon1_text.setTextColor(gray);
				icon3_text.setTextColor(gray);
				
				if (circleFrag == null) {
					circleFrag = new CircleFragment();
					transaction.add(R.id.body_frame, circleFrag);
				} else {
					transaction.show(circleFrag);
				}
				break;
			case 2:
			
				// 健康知识
				assessImage.setImageResource(R.drawable.frag_assess);
				circleImage.setImageResource(R.drawable.frag_circle);
				knowledgeImage.setImageResource(R.drawable.frag_knowledge_on);
				bt_family.setVisibility(View.INVISIBLE);
				bt_firstpage.setVisibility(View.INVISIBLE);
				tx_circle.setVisibility(View.INVISIBLE);
				tx_knowledge.setVisibility(View.VISIBLE);
				assessLine.setVisibility(View.INVISIBLE);
				circleLine.setVisibility(View.INVISIBLE);
				knowledgeLine.setVisibility(View.VISIBLE);
				icon3_text.setTextColor(lightgreen);
				icon1_text.setTextColor(gray);
				icon2_text.setTextColor(gray);
				
				if (knowledgeFrag == null) {
					knowledgeFrag = new KnowledgeFragment();
					transaction.add(R.id.body_frame, knowledgeFrag);
				} else {
					transaction.show(knowledgeFrag);
				}
				break;
			case 3:
			default:
				// 家庭组
				assessImage.setImageResource(R.drawable.frag_assess_on);
				circleImage.setImageResource(R.drawable.frag_circle);
				knowledgeImage.setImageResource(R.drawable.frag_knowledge);
				bt_family.setVisibility(View.VISIBLE);
				bt_firstpage.setVisibility(View.VISIBLE);
				tx_circle.setVisibility(View.INVISIBLE);
				tx_knowledge.setVisibility(View.INVISIBLE);
				bt_firstpage.setBackgroundResource(R.drawable.bt_top_lshift);
				bt_family.setBackgroundResource(R.drawable.bt_top_right_on);
				bt_firstpage.setTextColor(white);
				bt_family.setTextColor(lightgreen);
				assessLine.setVisibility(View.VISIBLE);
				circleLine.setVisibility(View.INVISIBLE);
				knowledgeLine.setVisibility(View.INVISIBLE);
				icon1_text.setTextColor(lightgreen);
				icon2_text.setTextColor(gray);
				icon3_text.setTextColor(gray);
				
				if (familyFrag == null) {
					familyFrag = new FamilyFragment();
					transaction.add(R.id.body_frame, familyFrag);
				} else {
					transaction.show(familyFrag);
				}
				break;
			}
			transaction.commit();
		}
		/**
		 * �����е�Fragment����Ϊ����״̬��
		 * @param transaction
		 *            ���ڶ�Fragmentִ�в���������
		 */
		private void hideFragments(FragmentTransaction transaction) {
			if (assessFrag != null) {
				transaction.hide(assessFrag);
			}
			if (circleFrag != null) {
				transaction.hide(circleFrag);
			}
			if (knowledgeFrag != null) {
				transaction.hide(knowledgeFrag);
			}
			if (familyFrag != null) {
				transaction.hide(familyFrag);
			}
		}
		// 设置
		public void setting(View v) { 
			Intent intent = new Intent();
			intent.setClass(MainActivity.this, Settings.class);
			startActivity(intent);
		
	}

	private int getSelectionState() {
		int state = 0;
		Intent i = getIntent();
		if(i != null && i.getExtras()!=null){
			Bundle b = i.getBundleExtra("attachment");
			state = b.getInt("selectionState");
		}
		return state;
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.icon1_lay:
		case R.id.bt_firstpage:
			setTabSelection(0);
			break;
		case R.id.icon2_lay:
			setTabSelection(1);
			break;
		case R.id.icon3_lay:
			setTabSelection(2);
			break;
		case R.id.bt_family:
			setTabSelection(3);
			break;
			default:
			break;
		}
		
	}
@Override
	protected void onResume() {
	String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
	String fileName = "/user_img_"+MyUtils.getUSERID()+".png";
	Bitmap bitmap = BitmapFactory.decodeFile(baseDir+fileName);
	if(bitmap != null){
		user_image.setImageBitmap(bitmap);
	}
	netstate=MyUtils.isNetworkConnected(getApplicationContext());		
	if(!netstate){
		Toast.makeText(MainActivity.this,"世界上最遥远的距离就是没有网络！",Toast.LENGTH_SHORT).show();
	}
	super.onResume();
	}
private class getMessageFromServer1 implements Runnable{

	@Override
	public void run() {
		String url=MyUtils.getUrl()+"family_validatesList?userid="+MyUtils.getUSERID();
		HttpGet request = new HttpGet(url);																
       HttpResponse httpResponse;
	try {
		httpResponse = new DefaultHttpClient().execute(request);
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
	        String jsonString = EntityUtils.toString(httpResponse.getEntity());
	        Log.i("message_jsonString", jsonString);
	        msg_json = new JSONObject(jsonString);
	        flag=(Boolean) msg_json.get("success");	
		}
	}catch (ClientProtocolException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}					       		       	
	
    Message handle_message = messageHandler.obtainMessage();
    
	if (flag) {				
		handle_message.what = 1;
		messageHandler.sendMessage(handle_message);				
	}
	else{
		handle_message.what = 2;
		messageHandler.sendMessage(handle_message);		
	}

}

	private Handler messageHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				int index = 0;
				try {
					message = msg_json.getJSONArray("obj");
					for(int i=0;i<message.length();i++){				
						index = message.getJSONObject(i).getInt("validateStatus");														
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(index == 0){
					Log.i("debug", "有未处理的消息！");
					reddot.setVisibility(View.VISIBLE);}
				else{
					reddot.setVisibility(View.INVISIBLE);
				}				
				break;
			case 2:
				reddot.setVisibility(View.INVISIBLE);
			default:
				break;
			}
		};
	};
}
private class getMessageFromServer2 implements Runnable{

	@Override
	public void run() {
		String url=MyUtils.getUrl()+"message_getFamily?userid="+MyUtils.getUSERID();
		HttpGet request = new HttpGet(url);																
       HttpResponse httpResponse;
	try {
		httpResponse = new DefaultHttpClient().execute(request);
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
	        String jsonString = EntityUtils.toString(httpResponse.getEntity());
	        Log.i("jsonString:", jsonString);
	        msg_reply_json = new JSONObject(jsonString);
	        flag=(Boolean) msg_reply_json.get("success");	        	
		}
	}catch (ClientProtocolException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}					       		       	
	
    Message handle_message2 = messageHandler.obtainMessage();
    
	if (flag) {				
		handle_message2.what = 1;
		messageHandler.sendMessage(handle_message2);				
	}
	else{
		handle_message2.what = 2;
		messageHandler.sendMessage(handle_message2);		
	}
		
	
	

}

	private Handler messageHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					replyMessageArray = msg_reply_json.getJSONArray("obj");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				int index = 0;
//				for(int i=0;i<message.length();i++){
//					try {
//						index = message.getJSONObject(i).getInt("validateStatus");
//						if(index == 0)break;
//						
//					} catch (JSONException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//					
//				}
				if(index == 0){
				reddot.setVisibility(View.VISIBLE);}
				else{
				
				}
				reddot.setVisibility(View.INVISIBLE);
				break;
			case 2:
				reddot.setVisibility(View.INVISIBLE);
			default:
				break;
			}
		};
	};
}
}
